package com.gjzt.business.media.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eastdigit.servlet.ReqBean;
import com.eastdigit.system.model.BusinessException;
import com.eastdigit.system.model.SqlBuilder;
import com.eastdigit.system.service.BaseService;
import com.eastdigit.util.DateUtil;
import com.eastdigit.util.StringUtil;
import com.gjzt.business.media.inter.MediaStopMapper;
import com.gjzt.business.media.model.MediaBus;
import com.gjzt.business.media.model.MediaStop;
import com.gjzt.business.utils.Constant;

@Service
public class ScheduleService extends BaseService {

    @Autowired
    private MediaStopMapper mediaStopMapper;
    @Autowired
    MediaBusService mediaBusService;

    public static void main(String[] args) {
        HashMap<String, String> dateResourceIdMap = new HashMap<String, String>();
        dateResourceIdMap.put("1", "1");
        System.out.println(dateResourceIdMap.get("2"));
    }

    /**
     * 查询上刊单资源明细
     * 
     * @param reqBean
     * @return
     */
    public JSONObject queryBillResource(ReqBean reqBean) {
        String billId = reqBean.getInfo("billId");
        if (StringUtils.isBlank(billId)) {
            throw new BusinessException("缺少参数!");
        }
        String sql = "SELECT pb.*, mr.RESOURCE_NAME FROM AD_PUBLISH_BILL_DETAIL pb "
                + "LEFT JOIN MEDIA_RESOURCE mr ON pb.RESOURCE_ID = mr.RESOURCE_ID WHERE pb.BILL_ID = '" + billId + "'";
        return queryTable(new SqlBuilder(sql).addWhereLike2("mr.RESOURCE_NAME", reqBean.getInfo("resourceName")),
                reqBean.getPageSize(), reqBean.getPageIndex());
    }

    /**
     * 查询
     * 
     * @param reqBean
     * @return
     */
    public JSONObject findSchedule(ReqBean reqBean) {
        JSONObject json = new JSONObject();
        
        String currentMonth = reqBean.getInfo("month");// 当前月份
        String lastOrNext = reqBean.getInfo("lastOrNext");// -1：上一月/年 1：下一月/年
        String monthOrYear = reqBean.getInfo("monthOrYear");// 1:年 2：月
        
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(StringUtil.isEmpty(currentMonth) ? new Date() : (DateUtil.parse(currentMonth + "-01")));
        
        if(StringUtil.isNotEmpty(lastOrNext) && StringUtil.isNotEmpty(monthOrYear)){
        	calendar.add(Integer.valueOf(monthOrYear), Integer.valueOf(lastOrNext));
        }
        String queryDateStr = DateUtil.formatDate(calendar.getTime());
        
        int year = calendar.get(Calendar.YEAR);
        ArrayList<String> monthsList = new ArrayList<String>();
        for (int i = 1; i <= 12; i++) {
            monthsList.add(year + "-" + i);
        }
        currentMonth = monthsList.get(calendar.get(Calendar.MONTH));
        JSONArray daysArray =  DateUtil.getDaysArray(queryDateStr);
        
        String resourceType = reqBean.getInfo("resourceType");
        
        SqlBuilder sql = new SqlBuilder(" select r.* ");
        if(Constant.MEDIA_TYPE_STOP.equals(resourceType)){
        	sql.appendSql(" ,s.ROAD_NAME,s.STOP_NAME,s.DIRECTION,s.LONGITUDE,s.LATITUDE,s.STOP_IMG,s.COUNTY STOP_COUNTY");
        	sql.appendSql(" from MEDIA_RESOURCE r");
            sql.appendSql(" LEFT JOIN MEDIA_STOP s ON r.STOP_ID = s.STOP_ID where 1=1");
            
           // sql.appendSql(" where r.MEDIA_TYPE = '" + reqBean.getInfo("mediaType") + "'");
            sql.addWhereLike("r.RESOURCE_CODE", reqBean.getInfo("resourceCode"));
            sql.addWhere("r.RESOURCE_ID", reqBean.getInfo("resourceId"));
            
            sql.addWhere("r.MEDIA_TYPE", reqBean.getInfo("mediaType"));
            sql.addWhere("s.COUNTY", reqBean.getInfo("county"));
            sql.addWhereLike("s.ROAD_NAME", reqBean.getInfo("roadName"));
            sql.addWhereLike("s.STOP_NAME", reqBean.getInfo("stopName"));
            
            sql.appendSql(" order by s.COUNTY,s.ROAD_NAME,s.STOP_NAME");
        }else if(Constant.MEDIA_TYPE_BUS.equals(resourceType)){
        	sql.appendSql(" ,b.VEHICLE_NO,b.PLATE_NO,b.LINE_NO,b.COMPANY_NAME,b.BUS_TYPE,b.BUS_IMG,b.STATUS BUS_STATUS");
        	sql.appendSql(" from MEDIA_RESOURCE r");
            sql.appendSql(" LEFT JOIN MEDIA_BUS b ON r.BUS_ID = b.BUS_ID where 1=1");
           // sql.appendSql(" where r.MEDIA_TYPE = '" + reqBean.getInfo("mediaType") + "'");
            
            sql.addWhereLike("r.RESOURCE_CODE", reqBean.getInfo("resourceCode"));
            sql.addWhere("r.RESOURCE_ID", reqBean.getInfo("resourceId"));
            
            sql.addWhere("r.MEDIA_TYPE", reqBean.getInfo("mediaType"));
            sql.addWhere("b.COMPANY_ID", reqBean.getInfo("companyId"));
            sql.addWhereLike("b.LINE_NO", reqBean.getInfo("lineNo"));
            sql.addWhereLike("b.PLATE_NO", reqBean.getInfo("plateNo"));
            sql.addWhereLike("b.VEHICLE_NO", reqBean.getInfo("vehicleNo"));
            sql.addWhere("b.BUS_TYPE", reqBean.getInfo("busType"));
            sql.addWhere("b.BUS_FLOOR", reqBean.getInfo("busFloor"));
            sql.addWhere("b.AIR_CONDITIONED", reqBean.getInfo("airConditioned"));
            sql.addWhere("b.BUS_ENERGY", reqBean.getInfo("busEnergy"));
            sql.addWhere("b.BUSINESS_TYPE", reqBean.getInfo("businessType"));
            sql.addWhere("b.STATUS", reqBean.getInfo("status"));
            
            sql.appendSql(" order by b.COMPANY_NAME");
        }
        System.out.println(sql.getSql());
        JSONObject dataJson = this.queryTable(sql, reqBean.getInfoInt("pageSize"),reqBean.getInfoInt("pageIndex"));
        
        int totalPages = dataJson.getInt("total") % reqBean.getInfoInt("pageSize") == 0 ? dataJson.getInt("total")
                / reqBean.getInfoInt("pageSize") : dataJson.getInt("total") / reqBean.getInfoInt("pageSize") + 1;
        JSONArray rows = dataJson.getJSONArray("rows");
        
        for (int i = 0; i < rows.size(); i++) {
            JSONObject o = rows.getJSONObject(i);
	        String resourceId = o.getString("resourceId");
            o.put("scheduleArray", getScheduleArray(resourceId, daysArray));
        }

        json.put("months", monthsList);// 全部月份
        json.put("currentMonth", monthsList.get(calendar.get(Calendar.MONTH)));// 当前查询月份
        json.put("lastYear", calendar.get(Calendar.YEAR) - 1);// 上一年
        json.put("nextYear", calendar.get(Calendar.YEAR) + 1);// 下一年
        json.put("daysArray", daysArray);// 当月日期、星期
        json.put("dataArray", rows);// 最终数据
        json.put("totalPages", totalPages);// 总页数
        return json;
    }

    public JSONArray getScheduleArray(String resourceId, JSONArray daysArray) {
        // 获得月初和月末
        String beginOfMonth = daysArray.getJSONObject(0).getString("date");
        String endOfMonth = daysArray.getJSONObject(daysArray.size() - 1).getString("date");
        HashMap<String, JSONObject> dateResourceIdMap = new HashMap<String, JSONObject>();
        getResouceInfoForLocked(dateResourceIdMap, resourceId, beginOfMonth, endOfMonth);// 处理已发布竞价资源信息
        getResouceInfoForWorkOff(dateResourceIdMap, resourceId, beginOfMonth, endOfMonth, "");// 处理售出资源信息
        getResouceInfoForPublished(dateResourceIdMap, resourceId, beginOfMonth, endOfMonth, "", "");// 处理上刊资源信息

        JSONArray scheduleArray = new JSONArray();
        for (int i = 0; i < daysArray.size(); i++) {
            JSONObject o = daysArray.getJSONObject(i);
            // 状态根据合同表、上刊单来确定（售出：合同表 已上刊：上刊表）
            JSONObject info = dateResourceIdMap.get(o.getString("date"));
            if (info == null) {
                JSONObject nullInfo = new JSONObject();
                nullInfo.put("status", Constant.SCHEDULE_CSS_FREE);;
                scheduleArray.add(nullInfo);
            } else {
                scheduleArray.add(info);
            }
        }
        return scheduleArray;
    }

    /**
     * 处理售出资源信息，查出合同、代理商信息
     * 
     * @param dateResourceIdMap
     * @param resourceId
     * @param beginOfMonth
     * @param endOfMonth
     */
    public void getResouceInfoForWorkOff(HashMap<String, JSONObject> dateResourceIdMap, String resourceId,
            String beginOfMonth, String endOfMonth, String customerId) {
        Date beginOfMonthDate = DateUtil.parse(beginOfMonth);// 月初
        Date endOfMonthDate = DateUtil.parse(endOfMonth);// 月末
        // 先查询合同表确定是否售出状态，再查询上刊表确定是否已上刊状态
        StringBuffer sql = new StringBuffer("select r.* ");
        sql.append(" ,c.CONTRACT_NO, c.CONTRACT_DATE");
        sql.append(" ,cu.CUSTOMER_ID, cu.CUSTOMER_NAME");
        sql.append(" FROM AD_CONTRACT_RESOURCE r ");
        sql.append(" INNER JOIN AD_CONTRACT c ON r.CONTRACT_ID = c.CONTRACT_ID ");
        sql.append(" LEFT JOIN AD_CUSTOMER cu ON c.CUSTOMER_ID = cu.CUSTOMER_ID ");
        sql.append(" where r.RESOURCE_ID = '").append(resourceId).append("'");
        sql.append(" and r.START_DATE <= '").append(endOfMonth).append("'");
        sql.append(" and r.END_DATE >= '").append(beginOfMonth).append("'");
        
        if (StringUtil.isNotEmpty(customerId)) {
        	  sql.append(" and cu.CUSTOMER_ID='").append(customerId).append("'");
        }
      
        
        JSONArray contractResources = this.query(sql.toString());

        for (int i = 0; i < contractResources.size(); i++) {
            JSONObject o = contractResources.getJSONObject(i);
            String startDateStr = o.getString("startDate");
            String endDateStr = o.getString("endDate");

            Date startDate = DateUtil.parse(startDateStr);
            Date endDate = DateUtil.parse(endDateStr);

            // 如果开始时间小于月初，则将开始时间调至月初；如果接受时间大于月末，则将结束时间调至月末

            if (startDate.before(beginOfMonthDate)) {// 如果开始时间小于月初，则将开始时间调至月初；
                startDate = beginOfMonthDate;
            }
            if (endDate.after(endOfMonthDate)) {// 如果结束时间小于月末，则将结束时间调至月末；
                endDate = endOfMonthDate;
            }

            Calendar startCalendar = Calendar.getInstance();
            startCalendar.setTime(startDate);
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.setTime(endDate);

            while (endCalendar.after(startCalendar) || endCalendar.equals(startCalendar)) {
                String dateStr = DateUtil.formatDate(startCalendar.getTime());// 日期
                JSONObject resouceInfo = dateResourceIdMap.get(dateStr);
                resouceInfo = resouceInfo == null ? new JSONObject() : resouceInfo;
                resouceInfo.put("contract", o);
                resouceInfo.put("status", Constant.SCHEDULE_CSS_WORKOFF);
                dateResourceIdMap.put(dateStr, resouceInfo);
                startCalendar.add(Calendar.DATE, 1);
            }
        }
    }

    /**
     * 处理已上刊资源信息，查出合同、上刊单、代理商信息、广告内容
     * 
     * 针对竞价功能排期的查询  :上刊审核通过、已完工为"已上刊";上刊待审核、提交了竞价单为"锁定"
     * 针对客户端上刊功能：上刊审核通过、已完工为"已上刊";反之为"锁定"
     * @param dateResourceIdMap
     * @param resourceId
     * @param beginOfMonth
     * @param endOfMonth
     */
	public void getResouceInfoForPublished(HashMap<String, JSONObject> dateResourceIdMap, String resourceId,
            String beginOfMonth, String endOfMonth, String modalBillId, String customerId) {
        // 先查询合同表确定是否售出状态，再查询上刊表确定是否已上刊状态
		
		StringBuffer sql = new StringBuffer("select r.BILL_ID, r.RESOURCE_ID, c.PUBLISH_TIME, c.PUBLISH_OFF_TIME ");
        sql.append(" ,c.BILL_NO, c.BILL_TYPE, c.APPLY_TIME ");
        sql.append(" ,cu.CUSTOMER_ID, cu.CUSTOMER_NAME, c.`STATUS`");
        sql.append(" FROM AD_PUBLISH_BILL_DETAIL r ");
        sql.append(" INNER JOIN AD_PUBLISH_BILL c ON r.BILL_ID = c.BILL_ID ");
        sql.append(" LEFT JOIN AD_CUSTOMER cu ON c.CUSTOMER_ID = cu.CUSTOMER_ID ");
        sql.append(" where r.RESOURCE_ID = '").append(resourceId).append("'");
        sql.append(" and c.PUBLISH_TIME <= '").append(endOfMonth).append("'");
        sql.append(" and c.PUBLISH_OFF_TIME >= '").append(beginOfMonth).append("'");

       /* if (StringUtil.isNotEmpty(modalBillId)) {
        	sql.append(" and r.BILL_ID <> '").append(modalBillId).append("'");
        }*/
        
        if (StringUtil.isNotEmpty(customerId)) {
      	  sql.append(" and cu.CUSTOMER_ID='").append(customerId).append("'");
        }
        
        sql.append(" order by r.PUBLISH_TIME ");
       
        JSONArray publishedArray = this.query(sql.toString());

        Date beginOfMonthDate = DateUtil.parse(beginOfMonth);// 月初
        Date endOfMonthDate = DateUtil.parse(endOfMonth);// 月末
        for (int i = 0; i < publishedArray.size(); i++) {
            JSONObject o = publishedArray.getJSONObject(i);
            String startDateStr = o.getString("publishTime");// 上刊时间
            String endDateStr = o.getString("publishOffTime");// 下刊时间
            String status = o.getString("status");// 上刊单状态
            
            Date startDate = DateUtil.parse(startDateStr);
            Date endDate = DateUtil.parse(endDateStr);

            // 如果开始时间小于月初，则将开始时间调至月初；如果接受时间大于月末，则将结束时间调至月末

            if (startDate.before(beginOfMonthDate)) {// 如果开始时间小于月初，则将开始时间调至月初；
                startDate = beginOfMonthDate;
            }
            if (endDate.after(endOfMonthDate)) {// / 如果结束时间小于月末，则将结束时间调至月末；
                endDate = endOfMonthDate;
            }

            Calendar startCalendar = Calendar.getInstance();
            startCalendar.setTime(startDate);
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.setTime(endDate);

            while (endCalendar.after(startCalendar) || endCalendar.equals(startCalendar)) {
                String dateStr = DateUtil.formatDate(startCalendar.getTime());// 日期
                JSONObject resouceInfo = dateResourceIdMap.get(dateStr);
                resouceInfo = resouceInfo == null ? new JSONObject() : resouceInfo;
                resouceInfo.put("bill", o);
                if(Constant.PUBLISH_BILL_STATUS_AUDIT_TRUE.equals(status) || Constant.PUBLISH_BILL_STATUS_FINISHED.equals(status)){// 审核通过、已完工
                	resouceInfo.put("status", Constant.SCHEDULE_CSS_PUBLISHED);
                }else {
                	resouceInfo.put("status", Constant.SCHEDULE_CSS_LOCKED);
                }
                dateResourceIdMap.put(dateStr, resouceInfo);
                startCalendar.add(Calendar.DATE, 1);
            }
        }
    }
    
    
    /**
     * 处理已发布竞价资源信息，查出竞价单信息
     * 
     * @param dateResourceIdMap
     * @param resourceId
     * @param beginOfMonth
     * @param endOfMonth
     */
    public void getResouceInfoForLocked(HashMap<String, JSONObject> dateResourceIdMap, String resourceId,
            String beginOfMonth, String endOfMonth) {
        Date beginOfMonthDate = DateUtil.parse(beginOfMonth);// 月初
        Date endOfMonthDate = DateUtil.parse(endOfMonth);// 月末
        StringBuffer sql = new StringBuffer(" select r.START_DATE,r.END_DATE,b.* ");
        sql.append(" from AD_BIDDING_RESOURCE r ");
        sql.append(" INNER JOIN AD_BIDDING b on r.BID_ID = b.BID_ID ");
        sql.append(" where r.RESOURCE_ID = '").append(resourceId).append("'");
        sql.append(" and r.START_DATE <= '").append(endOfMonth).append("'");
        sql.append(" and r.END_DATE >= '").append(beginOfMonth).append("'");
        sql.append(" order by r.START_DATE");
        
        JSONArray bidReourceArray = this.query(sql.toString());

        for (int i = 0; i < bidReourceArray.size(); i++) {
            JSONObject o = bidReourceArray.getJSONObject(i);
            String startDateStr = o.getString("startDate");
            String endDateStr = o.getString("endDate");

            Date startDate = DateUtil.parse(startDateStr);
            Date endDate = DateUtil.parse(endDateStr);

            // 如果开始时间小于月初，则将开始时间调至月初；如果接受时间大于月末，则将结束时间调至月末

            if (startDate.before(beginOfMonthDate)) {// 如果开始时间小于月初，则将开始时间调至月初；
                startDate = beginOfMonthDate;
            }
            if (endDate.after(endOfMonthDate)) {// 如果结束时间小于月末，则将结束时间调至月末；
                endDate = endOfMonthDate;
            }

            Calendar startCalendar = Calendar.getInstance();
            startCalendar.setTime(startDate);
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.setTime(endDate);

            while (endCalendar.after(startCalendar) || endCalendar.equals(startCalendar)) {
            	String dateStr = DateUtil.formatDate(startCalendar.getTime());// 日期
                JSONObject resouceInfo = dateResourceIdMap.get(dateStr);
                resouceInfo = resouceInfo == null ? new JSONObject() : resouceInfo;
                resouceInfo.put("bid", o);
                resouceInfo.put("status", Constant.SCHEDULE_CSS_LOCKED);
                dateResourceIdMap.put(dateStr, resouceInfo);
                startCalendar.add(Calendar.DATE, 1);
            }
        }
    }
    
    

    public JSONObject queryBillSources(ReqBean reqBean) {
        JSONObject json = new JSONObject();

        Date date = new Date();
        String nowDateStr = "";
        String currentMonth = reqBean.getInfo("month");// 当前月份
        String lastOrNext = reqBean.getInfo("lastOrNext");// -1：上一月 上一年 1：下一月
        String modalBillId = reqBean.getInfo("modalBillId");// 用于修改的时候去除掉已插入的上刊单
        // 下一年
        String monthOrYear = reqBean.getInfo("monthOrYear");// 1:年 2：月

        if (StringUtils.isBlank(currentMonth) && StringUtils.isBlank(lastOrNext)) {
            lastOrNext = "0";
            nowDateStr = DateUtil.formatDate(date);
        } else {
            nowDateStr = currentMonth + "-01";
        }

        Date nowDate = DateUtil.parse(nowDateStr);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(nowDate);
        if (StringUtils.isNotBlank(monthOrYear)) {
            calendar.add(Integer.valueOf(monthOrYear), Integer.valueOf(lastOrNext));// 1:年
            // 2：月
        }
        Date queryDate = calendar.getTime();// 需要查询的日期
        String queryDateStr = DateUtil.formatDate(queryDate);

        // 当前月份
        ArrayList<String> monthsList = new ArrayList<String>();
        for (int i = 1; i <= 12; i++) {
            monthsList.add(String.valueOf(calendar.get(Calendar.YEAR)) + "-" + i);
        }
        String sql = "select a.ID,a.START_DATE,a.END_DATE,a.PRICE,ac.*,mr.*,mt.MEDIA_NAME FROM AD_CONTRACT_RESOURCE a "
                + "LEFT JOIN AD_CONTRACT ac ON a.CONTRACT_ID = ac.CONTRACT_ID LEFT JOIN MEDIA_RESOURCE mr "
                + "ON mr.RESOURCE_ID = a.RESOURCE_ID LEFT JOIN MEDIA_TYPE mt on mr.MEDIA_TYPE = mt.MEDIA_ID where "
                + "ac.CUSTOMER_ID = '" + reqBean.getInfo("customerId") + "' and mt.PARENT_ID = '"
                + reqBean.getInfo("billType") + "'";
        if(StringUtils.isNotBlank(reqBean.getInfo("mediaId"))) {
            sql = sql + " and  mt.MEDIA_ID = '" + reqBean.getInfo("mediaId") + "'";
        }
        if (StringUtils.isNoneBlank(reqBean.getInfo("modalResourceId"))) {
            sql = sql + "AND a.RESOURCE_ID = '" + reqBean.getInfo("modalResourceId") + "'";
        }
        if (StringUtils.isNoneBlank(reqBean.getInfo("resourceCode"))) {
            sql = sql + " and mr.RESOURCE_CODE like '" + reqBean.getInfo("resourceCode") + "%'";
        }
        if (StringUtils.isNoneBlank(reqBean.getInfo("startDate"))) {
            sql = sql + " and ( a.END_DATE > '" + reqBean.getInfo("startDate") + "'";
            if (StringUtils.isNoneBlank(reqBean.getInfo("endDate"))) {
                sql = sql + " and a.START_DATE < '" + reqBean.getInfo("endDate") + "'";
            }
            sql = sql + ")";
        } else {
            if (StringUtils.isNoneBlank(reqBean.getInfo("endDate"))) {
                sql = sql + " and a.START_DATE < '" + reqBean.getInfo("endDate") + "'";
            }
        }
        sql = sql + " group by a.RESOURCE_ID";
        JSONObject dataJson = this.queryTable(new SqlBuilder(sql), reqBean.getInfoInt("pageSize"),
                reqBean.getInfoInt("pageIndex"));
        int totalPages = dataJson.getInt("total") / reqBean.getInfoInt("pageSize") + 1;
        JSONArray rows = dataJson.getJSONArray("rows");
        for (int i = 0; i < rows.size(); i++) {
            JSONObject o = rows.getJSONObject(i);
            String resourceId = o.getString("resourceId");
            String resourceName = o.getString("resourceName");
            String busId = o.optString("busId");
            String stopId = o.optString("stopId");
            if (StringUtils.isBlank(busId) && StringUtils.isNotBlank(stopId)) {
                MediaStop Stop = mediaStopMapper.selectByPrimaryKey(stopId);
                o.put("stopName", Stop.getStopName());
                o.put("roadName", Stop.getRoadName());
                o.put("direction", Stop.getDirection());
            } else if (StringUtils.isBlank(stopId) && StringUtils.isNotBlank(busId)) {
                MediaBus bus = mediaBusService.getMediaBus(busId);
                o.put("vehicleNo", bus.getVehicleNo());
                o.put("plateNo", bus.getPlateNo());
                o.put("lineNo", bus.getLineNo());
                o.put("companyId", bus.getCompanyId());
                o.put("companyName", bus.getCompanyName());
            }
            o.put("scheduleArray",
                    getBillScheduleArray(resourceId, resourceName,  DateUtil.getDaysArray(queryDateStr),
                            reqBean.getInfo("startDate"), reqBean.getInfo("endDate"), modalBillId, reqBean.getInfo("customerId")));
        }

        json.put("months", monthsList);// 全部月份
        json.put("currentMonth", monthsList.get(calendar.get(Calendar.MONTH)));// 当前查询月份
        json.put("lastYear", calendar.get(Calendar.YEAR) - 1);// 上一年
        json.put("nextYear", calendar.get(Calendar.YEAR) + 1);// 下一年
        json.put("daysArray",  DateUtil.getDaysArray(queryDateStr));// 当月日期、星期
        json.put("dataArray", rows);// 最终数据
        json.put("totalPages", totalPages);// 总页数
        return json;
    }

    public JSONArray getBillScheduleArray(String resourceId, String resourceName, JSONArray daysArray,
            String beginOfMonth, String endOfMonth, String modalBillId, String customerId) {
        // 获得月初和月末
        if (StringUtils.isBlank(beginOfMonth)) {
            beginOfMonth = daysArray.getJSONObject(0).getString("date");
        }

        if (StringUtils.isBlank(endOfMonth)) {
            endOfMonth = daysArray.getJSONObject(daysArray.size() - 1).getString("date");
        }
        HashMap<String, JSONObject> dateResourceIdMap = new HashMap<String, JSONObject>();
        getResouceInfoForWorkOff(dateResourceIdMap, resourceId, beginOfMonth, endOfMonth, customerId);// 处理售出资源信息
        getResouceInfoForPublished(dateResourceIdMap, resourceId, beginOfMonth, endOfMonth, modalBillId,customerId);// 处理上刊资源信息
        
        JSONArray scheduleArray = new JSONArray();
        for (int i = 0; i < daysArray.size(); i++) {
            JSONObject o = daysArray.getJSONObject(i);
            // 状态根据合同表、上刊单来确定（售出：合同表 已上刊：上刊表）
            JSONObject info = dateResourceIdMap.get(o.getString("date"));
            if (info == null) {
                JSONObject nullInfo = new JSONObject();
                nullInfo.put("status", Constant.SCHEDULE_CSS_FREE);
                // nullInfo.put("statusInfo", "空闲");
                nullInfo.put("resourceName", resourceName);
                scheduleArray.add(nullInfo);
            } else {
                info.put("date", o.getString("date"));
                info.put("resourceName", resourceName);
                scheduleArray.add(info);
            }
        }
        return scheduleArray;
    }

    /**
     * 查询具体资源历史广告信息
     * @param reqBean
     * @return
     */
	public JSONObject getResourceHistory(ReqBean reqBean) {
		String resourceId = reqBean.getInfo("resourceId");
		// 合同明细查经营商、上刊明细查广告主、广告内容
		JSONObject result = new JSONObject();
		SqlBuilder getContractInfosql = new SqlBuilder("SELECT acr.*,cus.CUSTOMER_NAME,cus.CUSTOMER_ID,ac.CONTRACT_NO FROM AD_CONTRACT_RESOURCE acr");
		getContractInfosql.appendSql(" LEFT JOIN AD_CONTRACT ac ON acr.CONTRACT_ID = ac.CONTRACT_ID");
		getContractInfosql.appendSql(" LEFT JOIN AD_CUSTOMER cus on ac.CUSTOMER_ID=cus.CUSTOMER_ID");
		getContractInfosql.appendSql(" where acr.RESOURCE_ID='" + resourceId + "'");
		getContractInfosql.appendSql(" ORDER BY acr.START_DATE desc");
		JSONArray contractInfoArray = this.query(getContractInfosql);
		for (int i = 0; i < contractInfoArray.size(); i++) {
			JSONObject o = contractInfoArray.getJSONObject(i);
			String startDate = o.getString("startDate");
			String endDate = o.getString("endDate");
			o.put("startDate",  DateUtil.formatDate(DateUtil.parse(startDate)));
			o.put("endDate",  DateUtil.formatDate(DateUtil.parse(endDate)));
			
			
			String customerId = o.getString("customerId");

			// 同一个资源，一个经营单位合同期内上刊多次
			SqlBuilder getPublishInfosql = new SqlBuilder("SELECT apbd.*,apb.BILL_NO FROM AD_PUBLISH_BILL apb");
			getPublishInfosql.appendSql(" LEFT JOIN AD_PUBLISH_BILL_DETAIL apbd ON apb.BILL_ID = apbd.BILL_ID");
			getPublishInfosql.appendSql(" where apbd.RESOURCE_ID='" + resourceId + "' and apb.CUSTOMER_ID='" + customerId + "'");
			JSONArray publishInfoArray = this.query(getPublishInfosql);
			for (int j = 0; j < publishInfoArray.size(); j++) {
				JSONObject ox = publishInfoArray.getJSONObject(j);
				String publishTime = ox.getString("publishTime");
				String publishOffTime = ox.getString("publishOffTime");
				ox.put("publishTime",  DateUtil.formatDate(DateUtil.parse(publishTime)));
				ox.put("publishOffTime",  DateUtil.formatDate(DateUtil.parse(publishOffTime)));
			}
			o.put("publishInfoArray", publishInfoArray);// 存放资源对应的上刊广告内容
		}
		result.put("contractInfoArray", contractInfoArray);
		return result;
	}
}